
tinymce.PluginManager.add('signature', function(editor, url){

    /**
     *  使用签名替换原签名区
    */
    const replaceSignature = (signature, data)=>{
        var time = getNowTimeFull();
        var date = (time || '').substring(0, 10);
        var type = $(signature).attr("data-type");
        var html = '';
        html += '<span class="sign-title-R1">'+ (type === "1" ? "工作者" : "检查者") +'</span>';
        html += '<span class="sign-img-R1"><img style="width:66px;height:40px" src="'+data+'"/></span>';
        html += '<span class="sign-user-info-R1">';
        html += '<span class="sign-user-R1">' + currentUser.realname + '</span>';
        html += '<span class="sign-date-R1">' + date + '</span>';
        html += '<svg style="position: absolute;top: 0px;right: 0px;" t="1668568116539" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2834" width="20" height="20"><path d="M512 832c-176.448 0-320-143.552-320-320S335.552 192 512 192s320 143.552 320 320-143.552 320-320 320m0-704C300.256 128 128 300.256 128 512s172.256 384 384 384 384-172.256 384-384S723.744 128 512 128" p-id="2835" fill="#909399"></path><path d="M649.824 361.376a31.968 31.968 0 0 0-45.248 0L505.6 460.352l-98.976-98.976a31.968 31.968 0 1 0-45.248 45.248l98.976 98.976-98.976 98.976a32 32 0 0 0 45.248 45.248l98.976-98.976 98.976 98.976a31.904 31.904 0 0 0 45.248 0 31.968 31.968 0 0 0 0-45.248L550.848 505.6l98.976-98.976a31.968 31.968 0 0 0 0-45.248" p-id="2836" fill="#909399"></path></svg>';
        html += '</span>';
        $(signature).html(html);
        $(signature).attr("data-sign",true);
        $(signature).attr("data-userid",userId);
        $(signature).attr("data-time",time);
        $(signature).css("width", "213px").css("display", "inline-flex");
        $(signature).removeAttr("data-mce-style");
        markColor();
        if (!$(signature).attr("data-id")) {
            $(signature).attr("data-id", Math.uuid().toLowerCase());
        }
    }

    const getNowTimeFull = () => {
        var myDate=new Date;
        var year=myDate.getFullYear(); //获取当前年
        var mon=myDate.getMonth()+1<10?"0"+(myDate.getMonth()+1):myDate.getMonth()+1; //获取当前月
        var date=myDate.getDate()<10?"0"+myDate.getDate():myDate.getDate(); //获取当前日
        var hour=myDate.getHours()<10?"0"+myDate.getHours():myDate.getHours();//获取当前时
        var minute=myDate.getMinutes()<10?"0"+myDate.getMinutes():myDate.getMinutes();//获取当前分
        return year+"-"+mon+"-"+date+" "+hour+":"+minute+":00";
    }

    /**
     * 清除签名
     */
    const clearSignature = ($target) => {
        $target.removeAttr("data-sign");
        $target.removeAttr("data-userid");
        $target.removeAttr("data-time");
        var type = $target.attr("data-type");
        $target.html("<span class='sign-empty'>" + (type === "1" ? "工作者签名" : "检查者签名") + "</span>");
        markColor();
    }

    /**
     * 光标放到最后
     */
    const goEnd = () => {
        editor.execCommand('selectAll');
        editor.selection.getRng().collapse(false);
        editor.focus();
    }

    /**
     * 签名后段落标记颜色
     */
    const markColor = () => {

        var $container = $(editor.contentDocument);
        // 如果已经包裹div，则解开
        $container.find(".signed-area").each((i, obj) => {
            var children = $(obj).children();
            if (children.length > 0) {
                $(children[0]).unwrap();
            }
        })
        // 如果已签名，找到段落标题与签名之前的所有元素，包裹div标色
        $container.find(".signature").each((i, obj) => {
            var $signature = $(obj);
            if ($signature.parent().is(".mce-offscreen-selection")){
                return true;
            }
            if ($signature.attr("data-sign") === "true" && $signature.attr("data-type") === "1") {
                var list = [];
                ($signature.parent().is("body") ? $signature: $signature.closest($container.find("body").children())).prevAll().each((j, prev) => {
                    if ($(prev).find(".signature[data-type='1']").length > 0) {
                        return false;
                    }
                    list.unshift(prev);
                });
                $(list).wrapAll('<div class="signed-area" data-signer="'+$signature.attr("data-userid")+'"></div>');
            }
        });
    }

    const openDialog = (signature)=>{
        signModal.show({
            type: $(signature).attr("data-type"),
            callback: (result) => {
                if (result.image) {
                    replaceSignature(signature, result.image);
                } else {
                    clearSignature($(signature));
                }
            }
        });
    };

    editor.ui.registry.addMenuButton('signature', {
        icon: 'highlight-bg-color',
        tooltip: '插入签名',
        fetch: function(callback) {
            var items = [
                {
                    type: 'menuitem',
                    text: '工作者签名',
                    onAction: ()=>{
                        var id = Math.uuid().toLowerCase();
                        editor.insertContent(editor.dom.createHTML('span', {
                            class:"signature",
                            contenteditable:false,
                            'data-type':"1",
                            'data-id':id,
                        }, '<span class="sign-empty">工作者签名</span>'))
                        changeSignaturePosition();
                    }
                },
                {
                    type: 'menuitem',
                    text: '检查者签名',
                    onAction: ()=>{
                        var id = Math.uuid().toLowerCase();
                        editor.insertContent(editor.dom.createHTML('span', {
                            class:"signature",
                            contenteditable:false,
                            'data-type':"2",
                            'data-id':id,
                        }, '<span class="sign-empty">检查者签名</span>'))
                        changeSignaturePosition();
                    }
                },
            ]
            callback(items)
        }
    });

    function changeSignaturePosition () {
        var parent = $(editor.selection.getNode());
        if (!parent.is("p")) {
            parent = parent.closest("p");
        }
        parent.css("text-align", "right");
        var signatures = parent.find(".signature");
        if (signatures.length === 1) {
            if ($(signatures[0]).attr("data-type") === "1") {
                $(signatures[0]).css("margin-right", "266px");
            }
        } else {
            signatures.css("margin-right", "");
        }
    }

    function getSignature(editor, elm) {
        return editor.dom.getParent(elm, '.signature');
    }

    editor.on('init', function () {
        const body = editor.contentDocument.body;
        if ($(body).hasClass("view_body") || $(body).hasClass("rev_body") || $(body).hasClass("audit_body")) {
            return;
        }
        body.addEventListener('click', function(e) {
            var signature = getSignature(editor, e.target);
            if (signature) {
                e.preventDefault();
                var type = $(signature).attr("data-type");
                if (!$(body).hasClass("feedback_body")) {
                    editor.notificationManager.open({
                        text: '编制工卡时无法签名',
                        type: 'error',
                        timeout: 3000,
                    });
                    return;
                }
                if (type === '1' && userType.indexOf("10") < 0) {
                    editor.notificationManager.open({
                        text: '无工作者权限',
                        type: 'error',
                        timeout: 3000,
                    });
                    return;
                }
                if (type === '2' && userType.indexOf("20") < 0) {
                    editor.notificationManager.open({
                        text: '无检查者权限',
                        type: 'error',
                        timeout: 3000,
                    });
                    return;
                }
                var userid = $(signature).attr("data-userid");
                if (userid && userid !== userId) {
                    editor.notificationManager.open({
                        text: '只能修改本人的签名',
                        type: 'error',
                        timeout: 3000,
                    });
                } else if ($(e.target).is("path") || $(e.target).is("svg")) {
                    clearSignature($(signature));
                } else if (window.signer) {
                    AlertUtil.showYesOrNoMessage("是否直接使用您已签署的签名？", function(obj){
                        if (obj === 'YES') {
                            replaceSignature(signature, window.signer);
                        } else {
                            openDialog(signature);
                        }
                    });
                } else {
                    openDialog(signature);
                }
            }
        }, false);
    });

     return {
        getMetadata: function () {
          return  {
            name: "signature",//插件名称
            url: "http://exampleplugindocsurl.com", //作者网址
          };
        }
     };

})